package org.example.validate;

import io.jsonwebtoken.Claims;
import org.example.model.dto.UserDetailDTO;
import org.example.util.JwtUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.web.authentication.AuthenticationConverter;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Map;
import java.util.Set;

/**
 * token转换器
 */
@Component
public class TokenAuthenticationConverter implements AuthenticationConverter {

    @Autowired
    private JwtUtils jwtUtils;


    @Override
    public Authentication convert(HttpServletRequest httpServletRequest) {
        String header = httpServletRequest.getHeader("Authorization");
        if (header == null) {
            return null;
        } else {
            header = header.trim();
            Claims claims = jwtUtils.getClaims(header);
            Map<String,Object> userMap = (Map<String,Object>)claims.get("user");
            String username = (String)userMap.get("username");
            ArrayList<GrantedAuthority> authorities = (ArrayList<GrantedAuthority>)userMap.get("authorities");
            UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken = new UsernamePasswordAuthenticationToken(username,
                    null,authorities);
            return usernamePasswordAuthenticationToken;
        }
    }
}
